import tkinter as tk
from sympy import symbols, Eq, solve
from tkinter import messagebox


def solve_equation(window, equation_entry):
    x = symbols('x')  # 定义符号变量x
    equation_str = equation_entry.get()  # 获取用户输入的方程
    try:
        # 将字符串转换为方程
        equation = Eq(eval(equation_str), 0)
        solutions = solve(equation, x)  # 解方程
        solution_str = ', '.join(str(sol) for sol in solutions)
        messagebox.showinfo("解方程结果", f"解为: {solution_str}")
    except Exception as e:
        messagebox.showerror("错误", f"无法解析方程: {str(e)}")


def switch_to_solve(window):
    window.withdraw()  # 隐藏当前窗口
    solve_window = tk.Toplevel()  # 创建新窗口
    solve_window.title("解方程")  # 界面标题
    solve_window.geometry("400x300")  # 窗口大小

    # 创建Label对象进行提示
    tk.Label(solve_window, text="请输入方程（例如：x**2 - 4）:").pack(pady=10)
    # 创建Entry对象让用户进行输入
    equation_entry = tk.Entry(solve_window, width=30)
    equation_entry.pack(pady=10)

    # 解方程按钮
    solve_button = tk.Button(solve_window, text="解方程", command=lambda: solve_equation(solve_window, equation_entry))
    solve_button.pack(pady=10)

    # 添加返回按钮，返回到原始计算器
    return_button = tk.Button(solve_window, text="返回",
                              command=lambda: [solve_window.destroy(), window.deiconify()])
    return_button.pack(pady=10)
